import { v4 as uuidv4 } from 'uuid'

export default class FakeEventSource {
  constructor(url) {
    console.log(`Connecting to ${url}`)
    this.intervalId = null // 初始化intervalId
    this.startMocking()
  }

  startMocking() {
    const fullMessage = 'This is a simulated streaming message from the server.'
    let uuid = uuidv4()
    let currentLength = 0
    const messageInterval = 100 // 每100ms发送一次消息

    let prevMes = ''
    let index = 2
    this.intervalId = setInterval(() => {
      // 使用this.intervalId存储定时器ID
      // 模拟逐字发送消息，直至完整消息发送完毕
      // debugger
      if (currentLength < fullMessage.length) {
        // debugger
        prevMes += fullMessage[currentLength]
        const eventData = {
          key: Date.now(),
          time: Date.now(),
          answerId: uuid,
          msg: prevMes // 发送下一个字符
        }

        const event = new CustomEvent('message', {
          detail: {
            data: JSON.stringify(eventData)
          }
        })

        window.dispatchEvent(event)
        currentLength++
        index++
        console.log('event', currentLength)
        console.log('index', index)
      } else {
        // debugger
        this.stopMocking() // 当消息发送完毕时停止模拟
        const eventData = ['DONE']

        const event = new CustomEvent('message', {
          detail: {
            data: JSON.stringify(eventData)
          }
        })

        window.dispatchEvent(event)
      }
    }, messageInterval)
  }

  stopMocking() {
    if (this.intervalId) {
      clearInterval(this.intervalId)
      this.intervalId = null
    }
  }

  addEventListener(eventType, callback) {
    window.addEventListener(eventType, (event) => {
      try {
        callback(event.detail)
      } catch (error) {
        console.log('error', error)
      }
    })
  }

  // 添加其他必要的方法和清理逻辑
}
